import React from 'react';
import {injectIntl, formatMessage} from './intl';
import PropTypes from 'prop-types';
import {Spin, Card, Button, Table, Row, Col, Popover, Form, message} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {hasPermissions, validateReportAgain} from './utils';
import {PERMISSION} from './constants';
import FileUpload from './FileUpload';
import TextInput from 'Shared/components/TextInput';
import {PAGE, DATE_FORMAT, FILES_API, TABLE, FORM_OPTIONS} from '../constants';
import routes from './routes';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {formatDateTime} from '../utils';
import styles from './style.css';
import {reportAgainInfo} from './api';
const {Description} = DescriptionList;
const FormItem = Form.Item;
export class ReportAgain extends React.PureComponent {
    state = {
        loading: false,
        validate: false,
        data: {
            replyComments: ''
        }
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleAbandonClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    handleSubmitClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    handleCloseClick = id => {
        this.setState({
            loading: true
        });
        this.props.onClickClose(id).then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    handleSolvedClick = id => {
        this.setState({
            loading: true
        });
        this.props.onClickSolved(id).then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    openLoding = () => {
        this.setState({loading: true});
    }
    closeLoding = () => {
        this.setState({loading: false});
    }
    handleFilterChange = (value, name) => {
        this.setState({
            data: {
                [name]: value,
            },
            hasOperat: true
        });
    };
    onChangeUpload = data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.reportAgainAttachments(data);
    }
    onChangeRemove= data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.removeReportAgainAttachments(data);
    }
    onSubmit = () => {
        const {rowVersion} = this.props.detail;
        const {reportAgainAttachments = []} = this.props.conditions;
        const {data} = this.state;
        const result = validateReportAgain(data, reportAgainAttachments);
        if(result) {
            this.setState({
                validate: true,
            });
            return message.warn(result);
        }
        reportAgainInfo(this.props.id, {
            replyComments: data.replyComments,
            attachments: reportAgainAttachments.map(m => ({
                fileId: m.fileId,
                fileName: m.fileName,
            })),
            rowVersion,
        })
            .then(res => {
                if(res.ok)
                    this.props.successReturn();
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    render() {
        const {id, detail, conditions, permissions, loading, onCancel} = this.props;
        const {options = [], details = []} = detail;
        const operations = [];
        const {reportAgainAttachments = []} = conditions;
        if(hasPermissions(permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(
                <Button key="update" href={`#${routes.update.format(id)}`} size="small">
                    {formatMessage({
                        id: 'reportAgain.btn.update',
                        defaultMessage: '编辑'
                    })}
                </Button>
            );
        if(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(options, PERMISSION.abandon))
            operations.push(
                <WrappedPopconfirm
                    id={id}
                    key="abandon"
                    title={formatMessage({
                        id: 'reportAgain.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={formatMessage({
                        id: 'reportAgain.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={formatMessage({
                        id: 'reportAgain.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleAbandonClick}>
                    <Button size="small">
                        {formatMessage({
                            id: 'reportAgain.btn.abandon',
                            defaultMessage: '作废'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );

        if(hasPermissions(permissions, PERMISSION.solved) && hasPermissions(options, PERMISSION.solved))
            operations.push(
                <WrappedPopconfirm
                    id={id}
                    key="solved"
                    title={formatMessage({
                        id: 'reportAgain.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={formatMessage({
                        id: 'reportAgain.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={formatMessage({
                        id: 'reportAgain.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleSolvedClick}>
                    <Button size="small">
                        {formatMessage({
                            id: 'reportAgain.btn.solved',
                            defaultMessage: '已解决'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(permissions, PERMISSION.close) && hasPermissions(options, PERMISSION.close))
            operations.push(
                <WrappedPopconfirm
                    id={id}
                    key="close"
                    title={formatMessage({
                        id: 'reportAgain.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={formatMessage({
                        id: 'reportAgain.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={formatMessage({
                        id: 'reportAgain.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleCloseClick}>
                    <Button size="small">
                        {formatMessage({
                            id: 'reportAgain.btn.close',
                            defaultMessage: '关闭'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(permissions, PERMISSION.transferToTechnicalCase) && hasPermissions(options, PERMISSION.transferToTechnicalCase))
            operations.push(
                <Button key="transferToTechnicalCase" href={`#${routes.transferToTechnicalCase.format(id)}`} size="small">
                    {formatMessage({
                        id: 'reportAgain.btn.transferToTechnicalCase',
                        defaultMessage: '转技术案例'
                    })}
                </Button>
            );
        if(hasPermissions(permissions, PERMISSION.reportAgain) && hasPermissions(options, PERMISSION.reportAgain))
            operations.push(
                <Button key="reportAgain" href={`#${routes.reportAgain.format(id)}`} size="small">
                    {formatMessage({
                        id: 'reportAgain.btn.reportAgain',
                        defaultMessage: '再上报'
                    })}
                </Button>
            );
        if(hasPermissions(permissions, PERMISSION.feedback) && hasPermissions(options, PERMISSION.feedback))
            operations.push(
                <Button key="feedback" href={`#${routes.feedback.format(id)}`} size="small">
                    {formatMessage({
                        id: 'reportAgain.btn.feedback',
                        defaultMessage: '反馈'
                    })}
                </Button>
            );
        const newDetails = details.map((item, index) => Object.assign(item, {no: index + 1}));
        const colums = [{
            title: formatMessage({
                id: 'reportAgain.column.no',
                defaultMessage: '序号'
            }),
            dataIndex: 'no',
        }, {
            title: formatMessage({
                id: 'reportAgain.column.replyDate',
                defaultMessage: '回复日期'
            }),
            dataIndex: 'replyDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'reportAgain.column.source',
                defaultMessage: '来源'
            }),
            dataIndex: 'source',
        }, {
            title: formatMessage({
                id: 'reportAgain.column.replyName',
                defaultMessage: '回复人名称'
            }),
            dataIndex: 'replyName',
        }, {
            title: formatMessage({
                id: 'reportAgain.column.replyComments',
                defaultMessage: '回复意见/再上报原因'
            }),
            dataIndex: 'replyComments',
        }, {
            title: formatMessage({
                id: 'reportAgain.column.action',
                defaultMessage: '操作'
            }),
            dataIndex: 'action',
            render: (text, record) => {
                const {attachments = []} = record;
                if(!attachments.length)
                    return '';
                const fileList = attachments.map(item => (<Description key={item.fileId}>
                    <a icon="download" href={`${FILES_API.files}/${item.fileId}`} size="small">
                        {item.fileName}</a></Description>));
                return (<Popover trigger="click" content={<DescriptionList col={1} size="large">
                    {fileList}
                </DescriptionList>}>
                    <a icon="download" size="small">
                        {formatMessage({
                            id: 'reportAgain.downloadFile',
                            defaultMessage: '下载附件'
                        })}</a>
                </Popover>);
            }
        }];
        return (
            <div className={styles.detail}>
                <Spin spinning={loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            className={styles.marginBottom}
                            title={formatMessage({
                                id: 'reportAgain.card.title',
                                defaultMessage: '基本信息'
                            })}>
                            <Row>
                                <Col key="code" {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'reportAgain.form.replyComments',
                                            defaultMessage: '再上报原因'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.validate && !this.state.data.replyComments ? 'error' : null}
                                        required>
                                        <TextInput
                                            name="replyComments"
                                            value={this.state.data.replyComments}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'reportAgain.form.attachments',
                                            defaultMessage: '附件'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <FileUpload onChange={this.onChangeUpload} onRemove={this.onChangeRemove} fileList={reportAgainAttachments} />

                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                    <Card
                        title={formatMessage({
                            id: 'reportAgain.details.title',
                            defaultMessage: '技术支持再上报情况清单'
                        })}
                        bordered={false}>
                        <Table
                            className="white-space-nowrap"
                            rowKey="id"
                            columns={colums}
                            pagination={false}
                            dataSource={newDetails} {...TABLE} />
                    </Card>
                    <Card>
                        <Row>
                            <Col className="col-align-right">
                                <Button key="submit"
                                    onClick={this.onSubmit}
                                    type="primary"
                                    loading={this.state.loading}>
                                    {formatMessage({
                                        id: 'reportAgain.btn.submit',
                                        defaultMessage: '保存'
                                    })}</Button>
                            </Col>
                        </Row>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" disabled={loading} onClick={onCancel}>
                        {formatMessage({
                            id: 'reportAgain.btn.retrun',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
            </div>
        );
    }
}
ReportAgain.propTypes = {
    conditions: PropTypes.object.isRequired,
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    isDealerUser: PropTypes.bool.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    removeReportAgainAttachments: PropTypes.func.isRequired,
    reportAgainAttachments: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickClose: PropTypes.func.isRequired,
    onClickSolved: PropTypes.func.isRequired,
    onClickSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired
};
import {connect} from 'react-redux';
import {getDetail, clearData, onClickAbandonForDetail, tableSearch,
    onClickSubmitForDetail, onClickClose, onClickSolved,
    reportAgainAttachments, removeReportAgainAttachments} from './actions';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    detail: getDetailData(state),
    conditions: getSubmitData(state),
    permissions: getPermissions(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    reportAgainAttachments: data => dispatch(reportAgainAttachments(data)),
    removeReportAgainAttachments: ({id}) => dispatch(removeReportAgainAttachments(id)),
    successReturn: () => {
        dispatch(tableSearch());
        ownProps.history.push(routes.query.url());
    },
    onClickAbandon: () =>
        dispatch(onClickAbandonForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onClickSubmit: id =>
        dispatch(onClickSubmitForDetail(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickClose: id =>
        dispatch(onClickClose(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onClickSolved: id =>
        dispatch(onClickSolved(id)).then(success => {
            if(success) dispatch(tableSearch({
                pageIndex: PAGE.index
            }));
            return success;
        }),
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(ReportAgain));
